<template>
  <NuxtLayout>
    <Head>
      <Title>{{ state.data.title }} - 详情</Title>
      <Meta name="description" :content="state.data.title" />
    </Head>
    <div class="app-page-detail bg-gray-100 relative">
      <ShareBar :is-liked="isLiked" :like-count="state.data.likeCount" @handleLike="onLike" />
      <el-container class="container">
        <el-main>
          <Loading :show="loading" />
          <div v-if="loading" class="h-120px" />
          <ClientOnly>
            <el-card shadow="hover" class="app-detail-header mb-5">
              <template #header>
                <div class="card-header flex justify-between items-center">
                  <div class="title">{{ state.data.title }}</div>
                  <div class="time"><Icon name="carbon:time" class="mr-2" />{{ state.data.createTime }}</div>
                </div>
              </template>
              <div class="center">
                <el-image class="app-cover-img w-full" :src="state.data.coverUrl" :preview-src-list="[state.data.coverUrl]" :initial-index="1" />
              </div>
            </el-card>
          </ClientOnly>
          <el-card shadow="hover" header="README">
            <div class="app-readme-content">
              <Viewer class="viewer" :tabindex="2" :sanitize="23" :value="state.data.md" :plugins="plugins" />
            </div>
          </el-card>
        </el-main>
        <el-aside width="350px" class="ml-2 app-article-detail-aside pt-5">
          <el-card shadow="hover" class="sticky1 mb-8" style="top: 20px; z-index: 1" header="简介">
            <ClientOnly>
              <el-collapse v-model="activeName" class="app-aside-collapse">
                <el-collapse-item title="介绍" name="1">
                  <div class="mb-3">{{ state.data.summary }}</div>
                  <el-space>
                    <NuxtLink :href="url" target="_blank">
                      <el-button type="success" :icon="View" round>查看仓库</el-button>
                    </NuxtLink>
                  </el-space>
                </el-collapse-item>
                <el-collapse-item title="基本信息" name="2" class="app-collapse-base">
                  <el-descriptions :column="2">
                    <el-descriptions-item label="作者">
                      <nuxt-link v-if="state.data.homepage" target="_blank" :to="state.data.homepage">{{ state.data.author?.slice(0, 6) }}</nuxt-link>
                      <template v-else>{{ state.data.author?.slice(0, 6) }}</template>
                    </el-descriptions-item>
                    <el-descriptions-item label="版本">Vue{{ state.data.version }}</el-descriptions-item>
                    <el-descriptions-item label="浏览量">{{ state.data.viewsCount }}</el-descriptions-item>
                    <el-descriptions-item label="加入时间">{{ state.data.createTime?.slice(0, 11) }}</el-descriptions-item>
                  </el-descriptions>
                </el-collapse-item>
                <el-collapse-item title="标签" name="3">
                  <div class="app-tags-list">
                    <el-tag v-for="(tag, index) in state.data.tags" :key="tag.id" :type="getTagType(index)" class="ml-2 mb-2">{{ tag.tagName }}</el-tag>
                    <PanelEmpty v-if="!state.data.tags?.length" />
                  </div>
                </el-collapse-item>
                <el-collapse-item title="后台语言" name="4">
                  <div class="app-tags-list">
                    <el-tag v-for="back in state.data.backend" :key="back.id" type="warning" class="ml-2 mb-2">{{ back.backendName }}</el-tag>
                    <PanelEmpty v-if="!state.data.backend?.length" />
                  </div>
                </el-collapse-item>
              </el-collapse>
            </ClientOnly>
          </el-card>
          <el-card shadow="hover" class="app-toc-card mb-8 sticky" header="目录">
            <ClientOnly>
              <PostAnchor />
            </ClientOnly>
          </el-card>
        </el-aside>
      </el-container>
    </div>
  </NuxtLayout>
</template>
<script setup lang="ts">
import { View } from '@element-plus/icons-vue'
import { set } from '@vueuse/core'
import { Viewer } from '@bytemd/vue-next'
import highlightssr from '@bytemd/plugin-highlight-ssr'
import gfm from '@bytemd/plugin-gfm'
import { ElMessage } from 'element-plus'
import { useArticleDetail, useUpdateArticle } from '~~/api/admin'
import { BasePagination } from '~~/config'
import { getTagType } from '~~/utils'
import 'highlight.js/styles/github-dark.css'

const route = useRoute()
const id = route.params.id
const { page, limit } = BasePagination
const loading = ref(true)
const state = reactive<any>({
  data: {},
  // 查询对象
  queryParams: {
    version: 3,
    navId: 1,
    title: '',
    id,
    page,
    limit,
  },
})
const LikeStoreKey = 'vue.admin.cn.likes.ids'
const activeName = ref(['1', '2', '3', '4', '5'])
const url = ref('')
const isLiked = ref(false)
const plugins = [highlightssr(), gfm()]
const likedIds = ref<any>([])
// 检查是否赞过
const checkLiked = (id: number) => likedIds.value.includes(id)

const initLike = () => {
  if (isBrowser()) {
    likedIds.value = JSON.parse(localStorage.getItem(LikeStoreKey) || '[]')
    if (likedIds.value.includes(+id)) {
      set(isLiked, true)
    }
  }
}

initLike()

// 获取详情
const getDetail = async () => {
  set(loading, true)

  const { data }: any = await useAsyncData('use_ArticleDetail', () => useArticleDetail(state.queryParams))

  state.data = data.value

  set(url, data.value.github || data.value.gitee)

  setTimeout(() => {
    set(loading, false)
  }, 200)
}

getDetail()

// 处理点赞成功
const handleLikeOk = (data: any) => {
  if (isBrowser()) {
    likedIds.value = likedIds.value.length ? [...likedIds.value, data.id] : [data.id]
    localStorage.setItem(LikeStoreKey, JSON.stringify(likedIds.value))
    set(isLiked, true)

    ElMessage({
      message: '点赞 +1',
      type: 'success',
    })
  }
}

// 处理点赞
const onLike = (count: number) => {
  if (checkLiked(+id)) {
    ElMessage({
      message: '感谢支持，您已赞过~！',
      type: 'warning',
    })
    return
  }

  useUpdateArticle({ id, likeCount: count }).then((res: any) => {
    res ? handleLikeOk(res) : ElMessage({ message: res?.error || '点赞失败，请稍候在试~！', type: 'error' })
  })
}
</script>
<style lang="scss">
.app-article-detail-aside.el-aside {
  overflow: inherit;
}
.markdown-body ol,
.markdown-body ul {
  list-style: disc;
}
</style>
